package com.car.web.controller;

import com.car.pojo.Post;
import com.car.service.SysPostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
@RequestMapping
public class PostController {

    @Autowired
    private SysPostService sysPostService;
    @GetMapping(value = "/list_v4")
    public String list(Model model, Post post, @RequestParam(defaultValue = "1") Integer pageNo) {
        Integer pageSize = 3;

        List<Post> list = sysPostService.list(post, pageSize, pageNo);
        model.addAttribute("list", list);
        Integer totalCount = sysPostService.selectSysUserCount(post);
        Integer totalPages = totalCount / pageSize;
        if (totalCount % pageSize != 0) {
            totalPages++;
        }
        model.addAttribute("list", list);
        model.addAttribute("totalCount", totalCount);
        model.addAttribute("totalPages", totalPages);
        model.addAttribute("pageNo", pageNo);
        model.addAttribute("pageSize", pageSize);
        return "index_v4";
    }

    @PostMapping("/add_v4")
    public String add(Post post) {
        int result = sysPostService.add(post);
        if (result > 0) {
            return "redirect:list_v4";
        }
        return "add_v4";
    }

    @GetMapping("/delete_v4")
    public String delete(@RequestParam Integer post_id) {
        int result = sysPostService.delete(post_id);
        if (result > 0) {
            return "redirect:list_v4";
        }
        return "delete_v4";
    }

    @PostMapping("/toEdit_v4")
    public String toEdit(Post post) {
        int result = sysPostService.update(post);
        if (result > 0) {
            return "redirect:list_v4";
        }
        return "toEdit_v4";
    }

    @GetMapping("/edit_v4")
    public String edit(Model model, Integer post_id) {
        Post post = sysPostService.getByid(post_id);
        model.addAttribute("post", post);

        return "edit_v4";
    }

    @GetMapping("/posts")
    public String getPosts(@RequestParam(required = false) String post_name) {
        if (post_name == null) {
            return "redirect:list_v4";  //如果没有提供postName，那么返回所有的posts
        } else {
            return sysPostService.selectPostsByPostName(post_name).toString(); //否则返回匹配的posts
        }
    }
}
